<?php

namespace App\Admin\Controllers;

use Encore\Admin\Controllers\AuthController as BaseAuthController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Validator;

class AuthController extends BaseAuthController
{
    protected function getFailedLoginMessage()
    {
        return '用户名或者密码错误';
    }


    protected function loginValidator(array $data)
    {
        return Validator::make($data, [
            $this->username()   => 'required',
            'password'          => 'required',
        ], [
            $this->username() . '.required' => '用户名必须填写',
            'password.required' => '密码必须填写'
        ]);
    }

    public function postLogin(Request $request)
    {
        $this->loginValidator($request->all())->validate();

        $credentials = $request->only([$this->username(), 'password']);
        $remember = $request->get('remember', false);

        if ($this->guard()->attempt($credentials, $remember)) {
            $res = $this->sendLoginResponse($request);
            $this->sendSingleToken($this->guard()->user(), $request);
            return $res;
        }

        return back()->withInput()->withErrors([
            $this->username() => $this->getFailedLoginMessage(),
        ]);
    }

    public function sendSingleToken($member, Request $request) {
        $time = time();
        $singleToken = md5($member->id . $time);
        Cache::put($member->id, $time);
        $request->session()->put('SINGLE_TOKEN', $singleToken);
    }
}
